package org.eclipse.moquette.server;

import org.eclipse.moquette.server.netty.NettyAcceptor;
import org.eclipse.moquette.spi.impl.SimpleMessaging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Properties;

import static org.eclipse.moquette.commons.Constants.PERSISTENT_STORE_PROPERTY_NAME;

/**
 * Created by alex on 15-5-29.
 */
public class Server {

    private static final Logger LOG = LoggerFactory.getLogger(Server.class);

    private ServerAcceptor m_acceptor;
    SimpleMessaging messaging;
    Properties m_properties;

    public static void main(String[] args) throws Exception{
        final Server server = new Server();
        server.startServer();
        System.out.println("Server started, version 0.7-SNAPSHOT");

        //关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                server.stopServer();
            }
        });
    }

    public void startServer() throws IOException {
        String configPath = System.getProperty("moquette.path", null);
        startServer(new File(configPath, "config/moquette.conf"));
    }

    public void startServer(File configFile) throws IOException {
        LOG.info("Using config file: " + configFile.getAbsolutePath());

        ConfigurationParser confParser = new ConfigurationParser();

        try {
            confParser.parse(configFile);
        } catch (ParseException pex) {
            LOG.warn("An error occurred in parsing configuration, fallback on default configuration", pex);
        }

        m_properties = confParser.getProperties();
        startServer(m_properties);
    }

    public void startServer(Properties configProps) throws IOException {
        ConfigurationParser confParser = new ConfigurationParser(configProps);
        m_properties = confParser.getProperties();
        LOG.info("Persistent store file: " + m_properties.get(PERSISTENT_STORE_PROPERTY_NAME));

        messaging = SimpleMessaging.getInstance();
        messaging.init(m_properties); //根据部分配置 启动入站的事件

        m_acceptor = new NettyAcceptor();
        m_acceptor.initialize(messaging, m_properties); //配置netty 添加SimpleMessaging处理Handler
    }

    public void stopServer() {
        LOG.info("Server stopping...");
        messaging.stop();
        m_acceptor.close();
        LOG.info("Server stopped");
    }

    public Properties getProperties() {
        return m_properties;
    }
}
